﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdvanceLib.ScriptCore;
using AdvanceLib.ScriptCore.DebugCore;

namespace AdvanceLib.Extension.XseScript.DebugPasses
{
    public class ParameterCountPass : CommandPass, IFinalPass
    {
        #region Constructors
        public ParameterCountPass(XseExtensionProvider provider)
        {
            this._provider = provider;
        }
        #endregion

        #region Fields
        private XseExtensionProvider _provider;

        private CommandData _command;
        private int _paramCount = 0;
        private int _lastErrorLine = 0;
        #endregion

        #region Methods
        private void ValidateLastResult(DebugResult result)
        {
            if (this._command != null &&
                (this._paramCount > this._command.Parameters.Count ||
                this._paramCount < this._command.Parameters.Count))
            {
                result.Errors.Add(new DebugError()
                {
                    Line = this.CurrentLineIndex,
                    Message = "Command " + '"' + this._command.Name + '"' + " expects " +
                              this._command.Parameters.Count.ToString() + " parameter(s)."
                });
                this._lastErrorLine = this.CurrentLineIndex;
            }
        }
        #endregion

        #region IterativeCommandDebugger Members
        public override void Pass(DebugResult result, string linePart)
        {
            if (this.CurrentLinePartIndex == 0)
            {
                this._command = this._provider.Database.GetCommandDataByName(linePart);
                this._paramCount = 0;
            }
            else if (this._command != null)
            {
                this._paramCount++;
            }
        }
        #endregion

        #region IFinalCommandDebugger Member
        public void FinalPass(DebugResult result)
        {
            if (this._lastErrorLine != this.CurrentLineIndex) this.ValidateLastResult(result);
        }
        #endregion
    }
}
